<?php
/**
 * Created by PhpStorm.
 * User: 84071
 * Date: 2018-03-23
 * Time: 16:21
 */
namespace app\common\model;
use think\Db;
use think\db\Query;
use think\Model;

class Comment extends Model{
    // 开启自动写入时间戳
    protected $autoWriteTimestamp = true;
    protected $insert = ['addtime'];
    protected $type = [
        'addtime'    => 'timestamp',
    ];
    // 定义时间戳字段名
    protected $createTime = 'addtime';
    protected $updateTime = false;
    // 启用状态
    protected function getclasszhAttr($value,$data){
        $class = [ 0 => '订单',1 => '产品',2 => '文章',3 => '会员'];
        return $class[$data['class']];
    }
    /**
     * 查询列表
     */
    public function getList($data){
        $webdb = webdb();
        $aid = empty($data['aid']) ? null:$data['aid'];
        $uid = empty($data['uid']) ? null:$data['uid'];
        $class = empty($data['class']) ? null:$data['class'];
        $num = empty($data['num']) ? '20':$data['num'];
        $page = empty($data['page']) ? '1':$data['page'];
        $status = empty($data['status']) ? '1':$data['status'];
        //  构造查询语句
        $query = new Query();
        $query = $query->name('comment');

        if(!empty($aid)){
            $query = $query->where('aid',$aid);
            $map['aid'] = $aid;
        }
        if(!empty($class)){
            $query = $query->where('class','in',$class);
            $map['class'] = array('in',$class);
        }
        if(!empty($uid)){
            $query = $query->where('uid',$uid);
            $map['uid'] = $uid;
        }
        if($status == '1'){
            $query = $query->where('status','1');
            $map['status'] = '1';
        }
        $query = $query->order("addtime desc")->limit($num)->page($page);
        //  执行sql语句halt($query);
        $_listdata = Db::select($query);
        //  获取所有数量
        $listmun = $this->where($map)->count();
        $pages = ceil($listmun/$num);
        if(empty($_listdata)){
            return false;
        }
        $listdata = null;
        $usermodel = new UserData();
        foreach ($_listdata as $k => $v){
            $user = $usermodel->where('uid',$v['uid'])->column('uid,username,uicon,uniname');
            $user = $user[$v['uid']];
            $user['fusername'] = $user['uniname']?substr($user['username'],0,3)."****".substr($user['username'],7,4):$user['uniname'];
            if(!empty($user['uicon'])){
                $user['uicon'] = '/'.$webdb['updir'].'/'.$user['uicon'];
            }
            $v['comment'] = str_replace("\n","<br/>",$v['comment']);
            $v['addtime'] = date("Y-m-d H:i:s",$v['addtime']);
            $v['user'] = $user;
            $listdata[$k] = $v;
        }
        $res = array(
            'list' => $listdata,
            'pages' => $pages,
            'page' => $page,
            'pagenum' => $listmun,
        );
        return $res;
    }
}